package com.zhangye.test.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangye.test.mapper.SmsSessionMapper;
import com.zhangye.test.model.SmsSession;

@Service
public class SendMsgService {


	@Autowired
	private SmsSessionService smsSessionService;// 验证码
	@Autowired
	private SmsSessionMapper smsSessionMapper;
	
	
	private static final String USERNAME = "hbydggdx";
	private static final String PWDMD5 = "7240835ee7502289c76f5e9bd4cddb8d";
	private static final String ENCODE = "UTF-8";
	private static final String APIKEY = "343bee5b74772b35dca3d877e9c0d401";
	
	private String ARREARAGE = "【AR在线】尊敬的用户，截止到现在，您的AR扫描次数已使用完毕，为了不影响您作品的正常扫描使用，请您及时续费，如已续费，请忽略，谢谢合作！";
	private String VERIFICATION = "【AR在线】尊敬的AR在线用户，您的短信验证码是：%s，请在三分钟使用，超时请重新申请。";

	
	/**
	 * 发送短信
	 * success:msgid  提交成功。
	error:msgid  提交失败  
	error:Missing username  用户名为空
	error:Missing password  密码为空
	error:Missing apikey  APIKEY为空
	error:Missing recipient  手机号码为空
	error:Missing message content  短信内容为空
	error:Account is blocked  帐号被禁用
	error:Unrecognized encoding  编码未能识别
	error:APIKEY or password_md5 error  APIKEY或密码错误
	error:Unauthorized IP address  未授权 IP 地址
	error:Account balance is insufficient  余额不足
	
	type:0 验证，1欠费
	
	 * 作者： 张叶
	 * 创建时间：2018年8月20日  上午11:02:06
	 */
	public int sendMsg(String telphone,int type){
		int i = 0;
		String content = "";
		String validate = "";
		if(type == 0){//验证
			validate = this.validate();
			content = VERIFICATION.format(VERIFICATION, validate);
		}else{
			content = ARREARAGE;
		}
		String result = this.sendSms(content, telphone);
		if(result.startsWith("succes")){
			SmsSession ss = new SmsSession();
			ss.setCreateDate(new Date());
			ss.setUserName(telphone);
			if(type == 0){
				ss.setSessionId(validate);	
			}
			if(smsSessionService.findByTelphone(telphone) != null){
				i = smsSessionService.updateSession(ss);
			} else {
				i = smsSessionService.save(ss);
			}
		}
		return i;
	}
	
	
	public String validate(){
		Random random = new Random();
		String result="";
		for (int i=0;i<6;i++)
		{
			result+=random.nextInt(10);
		}
		return result;
	}
	
	public String sendSms(String content,String telphone){
		String result = "";
		System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时：30秒
		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时：30秒
		// 新建一个StringBuffer链接
		StringBuffer buffer = new StringBuffer();
		try {
			String contentUrlEncode = URLEncoder.encode(content, ENCODE); // 对短信内容做Urlencode编码操作。注意：如
			// 把发送链接存入buffer中，如连接超时，可能是您服务器不支持域名解析，请将下面连接中的：【m.5c.com.cn】修改为IP：【115.28.23.78】
			buffer.append("http://m.5c.com.cn/api/send/index.php?username="
					+ USERNAME + "&password_md5=" + PWDMD5 + "&mobile="
					+ telphone + "&apikey=" + APIKEY + "&content="
					+ contentUrlEncode + "&encode=" + ENCODE);
			// 把buffer链接存入新建的URL中
			URL url = new URL(buffer.toString());
			// 打开URL链接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			// 获取返回值
			result = reader.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}